<template>
  <el-dialog
    :close-on-click-modal="false"
    title="项目资金投入及回收计划"
    :visible.sync="show"
    width="1000px"
    center
  >
    <el-form ref="form" :rules="rules" style="padding-top: 10px;" :model="form" label-width="100px">
      <div class="com-form-title">基础信息</div>
      <el-row>
        <el-col :span="8">
          <el-form-item label="项目名称" prop="projectName">
            <!-- <el-input v-model="form.projectName" :disabled="disableForm" /> -->
            <el-input v-model="form.projectName" readonly :disabled="disableForm || optType !== 'add'" @click.native="optType === 'add' ? showTargetSetListModal = true : null">
              <i slot="suffix" class="el-input__icon el-icon-circle-plus-outline" />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="年度月份" prop="yearMonthInfo">
            <!-- <el-input v-model="form.yearMonthInfo" :disabled="disableForm" /> -->
            <el-date-picker
              v-model="form.yearMonthInfo"
              type="month"
              value-format="yyyy-MM"
              :disabled="disableForm"
              placeholder="选择月"
              style="width: 100%;"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="资金回收" prop="fundRecovery">
            <el-input v-model="form.fundRecovery" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="资金投入" prop="fundInvestment">
            <el-input v-model="form.fundInvestment" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="差额" prop="difference">
            <el-input v-model="form.difference" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" :disabled="disableForm" />
          </el-form-item>
        </el-col>

      </el-row>

      <!-- <div style="padding-bottom: 10px;">
        <el-button type="primary" @click="showTargetSetListModal = true">引入计划</el-button>
        <el-button type="primary" @click="deleteDetail">删除计划</el-button>
      </div> -->
      <com-table
        :data="targetList"
        :columns="columns"
        :no-page="true"
      >
        <!-- <template v-slot:parentId="{row}">
          <el-input v-model="row.parentId" />
        </template>
        <template v-slot:sequence="{row}">
          <el-input v-model="row.sequence" />
        </template>
        <template v-slot:content="{row}">
          <el-input v-model="row.content" />
        </template> -->
        <template v-slot:amount="{row}">
          <el-input v-if="row.sequence !== '一' && row.sequence !== '二'" v-model="row.amount" @input="inputAmount(row)" />
        </template>
        <template v-slot:remark="{row}">
          <el-input v-if="row.sequence !== '一' && row.sequence !== '二'" v-model="row.remark" />
        </template>

      </com-table>
      <el-button style="margin-top:10px;" type="primary" @click="showFileModal = true">附件资料({{ fileList.length }})</el-button>
      <file-uploader v-model="fileList" :show-modal.sync="showFileModal" :disabled="disableForm" :can-download="optType==='detail'" />
      <project-list :show-modal.sync="showTargetSetListModal" :select-search="false" @getSelectedRows="getSelectedRows" />

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="show = false">取 消</el-button>
      <el-button type="primary" @click="saveDoc">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addProjectFundPushPopInfo, updateProjectFundPushPopInfo, getProjectFundPushPopInfoDetail } from '@/api/planManage'
import { getAreaList } from '@/api/common'
import { workflowStatus } from '@/utils/dicData'
import fileUploader from '@/components/FileUploader'
import ProjectList from '@/components/TreeModal/project'

export default {
  name: 'AddProjectFundPushPopInfo',
  components: {
    fileUploader,
    ProjectList
  },
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    optType: {
      type: String,
      default: 'add'
    },
    dir: {
      type: Object,
      default() {
        return {}
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      showFileModal: false,
      selectRow: null,
      targetList: [
        {
          sequence: '一',
          content: '资金回收',
          amount: '',
          remark: ''
        },
        {
          sequence: '1',
          content: '累计货币工作量（元）',
          amount: '',
          remark: ''
        },
        {
          sequence: '2',
          content: '累计应回款金额（元）',
          amount: '',
          remark: ''
        },
        {
          sequence: '3',
          content: '截止至上月累计应回款金额（元）',
          amount: '',
          remark: ''
        },
        {
          sequence: '4',
          content: '本月回款金额（元）',
          amount: '',
          remark: ''
        },
        {
          sequence: '二',
          content: '资金投入',
          amount: '',
          remark: ''
        },
        {
          sequence: '1',
          content: '累计成本（元）',
          amount: '',
          remark: ''
        },
        {
          sequence: '2',
          content: '累计应支付金额（元）',
          amount: '',
          remark: ''
        },
        {
          sequence: '3',
          content: '截止至上月累计应支付金额',
          amount: '',
          remark: ''
        },
        {
          sequence: '4',
          content: '本月支付金额',
          amount: '',
          remark: ''
        }
      ],
      workflowStatus,

      addType: '', // same   under
      visible: false,
      showAdd: false,
      selectedNode: null,
      form: {
        projectName: '',
        yearMonthInfo: '',
        fundRecovery: '',
        fundInvestment: '',
        difference: '',
        remark: '',
        addWorkflowId: '',
        status: '',
        founderName: '',
        createTime: ''
      },
      columns: [
        {
          label: '序号',
          prop: 'sequence',
          width: '60'
        },
        {
          label: '内容',
          prop: 'content'
        },
        {
          label: '金额',
          slot: 'amount'
        },
        {
          label: '备注',
          slot: 'remark'
        }
      ],
      showTargetSetListModal: false,
      fileList: [
      ],
      rules: {
        projectName: [
          { required: true, message: '项目名称', trigger: 'change' }
        ]
        // unifiedSocialCreditCode: [
        //   { required: true, message: '统一社会信用代码', trigger: 'change' }
        // ]
      },
      provinceData: [],
      cityData: []
    }
  },
  computed: {
    disableForm() {
      return this.optType === 'detail'
    },
    show: {
      get() {
        return this.showModal
      },
      set(val) {
        this.$emit('update:showModal', val)
      }
    }
  },
  watch: {
    showModal(val) {
      if (val && this.optType !== 'add') {
        this.getDocDetail(this.data.id)
        // this.$nextTick(() => {
        //   Object.keys(this.form).forEach(key => {
        //     const source = this.data[key]
        //     if (typeof source === 'boolean') {
        //       this.form[key] = source ? 1 : 0
        //     } else {
        //       this.form[key] = source
        //     }
        //   })
        // })
      } else if (!val) {
        this.fileList = []
        this.$refs.form.resetFields()
      } else {
        this.initTableData()
      }
    }
  },
  mounted() {
    // this.getRegionData()
  },
  methods: {
    getSelectedRows(obj) {
      // 将值赋给
      this.form.projectName = obj.row.projName
    },
    initTableData() {
      this.targetList = [
        {
          sequence: '一',
          content: '资金回收',
          amount: '',
          remark: ''
        },
        {
          sequence: '1',
          content: '累计货币工作量（元）',
          amount: '',
          remark: ''
        },
        {
          sequence: '2',
          content: '累计应回款金额（元）',
          amount: '',
          remark: ''
        },
        {
          sequence: '3',
          content: '上月累计应回款金额（元）',
          amount: '',
          remark: ''
        },
        {
          sequence: '4',
          content: '本月回款金额（元）',
          amount: '',
          remark: ''
        },
        {
          sequence: '二',
          content: '资金投入',
          amount: '',
          remark: ''
        },
        {
          sequence: '1',
          content: '累计成本（元）',
          amount: '',
          remark: ''
        },
        {
          sequence: '2',
          content: '累计应支付金额（元）',
          amount: '',
          remark: ''
        },
        {
          sequence: '3',
          content: '上月累计应支付金额',
          amount: '',
          remark: ''
        },
        {
          sequence: '4',
          content: '本月支付金额',
          amount: '',
          remark: ''
        }
      ]
    },
    provinceChange(e) {
      const selectedData = this.provinceData.filter(val => val.name === e)[0]
      if (selectedData) {
        this.form.city = ''
        const params = {
          parentCode: selectedData.code,
          areaType: 2
        }
        getAreaList(params).then(res => {
          this.cityData = res.data || []
        })
      }
    },
    getDocDetail(id) {
      let recycle = 0 // 回收
      let putInto = 0 // 投入
      getProjectFundPushPopInfoDetail({ projectFundPushPopInfoId: id }).then(res => {
        const { lstAttachment, lstProjectFundPushPopDetail, projectFundPushPopInfo } = res.data || {}
        if (lstAttachment && lstAttachment.length > 0) {
          this.fileList = lstAttachment
        }
        Object.keys(this.form).forEach(key => {
          const source = projectFundPushPopInfo[key]
          if (typeof source === 'boolean') {
            this.form[key] = source ? 1 : 0
          } else {
            this.form[key] = source
          }
        })
        this.targetList = lstProjectFundPushPopDetail
        lstProjectFundPushPopDetail.forEach((item, index) => {
          if (item.amount && index < 5) {
            recycle = recycle + Number.parseFloat(item.amount)
          }
          if (item.amount && index > 5) {
            putInto = putInto + Number.parseFloat(item.amount)
          }
        })
      })
      this.form.fundRecovery = recycle
      this.form.fundInvestment = putInto
      this.form.difference = (recycle - putInto).toFixed(2)
      this.$forceUpdate()
    },
    // getRegionData() {
    //   getAreaList({ areaType: '1' }).then(res => {
    //
    //     this.provinceData = res.data || []
    //   })
    // },
    deleteDetail() {
    },
    saveDoc() {
      if (this.optType === 'detai') {
        this.show = false
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = {
            projectFundPushPopInfo: {
              ...this.form,
              ...this.optType === 'edit' ? {
                id: this.data.id
              } : {}
            },
            lstAttachment: this.fileList,
            lstProjectFundPushPopDetail: this.targetList.filter(item => item.sequence !== '一' || item.sequence !== '二')
          }
          const fn = this.optType === 'add' ? addProjectFundPushPopInfo : updateProjectFundPushPopInfo
          fn(params).then(res => {
            if (res.code === '0001') {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.show = false
              this.$emit('freshList')
              this.$refs.form.resetFields()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }
      })
    },
    inputAmount(row) {
      // 计算差额
      let recycle = 0 // 回收
      let putInto = 0 // 投入
      this.targetList.forEach((item, index) => {
        if (item.amount && index < 5) {
          recycle += Number.parseFloat(item.amount)
        }
        if (item.amount && index > 5) {
          putInto += Number.parseFloat(item.amount)
        }
      })
      this.form.fundRecovery = recycle.toFixed(2)
      this.form.fundInvestment = putInto.toFixed(2)
      this.form.difference = (recycle.toFixed(2) - putInto.toFixed(2)).toFixed(2)
      this.$forceUpdate()
    }
  }
}
</script>

<style lang="scss" scoped>
.com-form-title{
  font-size: 14px;
  font-weight: bold;
  line-height: 35px;
  color: #409EFF;
  border-bottom: 1px solid #dedede;
  margin-bottom: 6px;
}
</style>
